//
//  ExBluetoothViewController.m
//  OC-Example
//
//  Created by apang on 2018/7/31.
//  Copyright © 2018年 apang.men All rights reserved.
//

#import "ExBluetoothViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ExBluetoothViewController ()
<CBCentralManagerDelegate,CBPeripheralDelegate,UITableViewDataSource,UITableViewDelegate>
{
    CBCentralManager *centralManager;//客户端管理
    UITableView *_tableView;
    BOOL isScan;
    NSMutableArray *serviceArr;
    CBPeripheral *discoveredPeripheral;
    CBCharacteristic *characteristic;
}
@end

@implementation ExBluetoothViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _tableView = [[UITableView alloc] init];

    _tableView.delegate = self;

    _tableView.dataSource = self;

    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [self.view addSubview:_tableView];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[_tableView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[_tableView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)]];
    // 指定当前类为代理对象，所以其需要实现CBCentralManagerDelegate协议
    // 如果queue为nil，则Central管理器使用主队列来发送事件
    centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    isScan = NO;
    serviceArr = [NSMutableArray array];
    self.title = @"蓝牙扫描";
    UIBarButtonItem * off = [[UIBarButtonItem alloc] initWithTitle:@"off" style:UIBarButtonItemStyleDone target:self action:@selector(sendClose)];
    UIBarButtonItem * on = [[UIBarButtonItem alloc] initWithTitle:@"on" style:UIBarButtonItemStyleDone target:self action:@selector(sendOpen)];
    self.navigationItem.rightBarButtonItems = @[off,on];
}

- (void)sendData:(NSData *)data {
    //        Byte command[1] = {0x11};
    //        NSData *data = [NSData dataWithBytes:command length:sizeof(command)];
    //        [peripheral writeValue:data forCharacteristic:characteristic  type:CBCharacteristicWriteWithResponse];
    if (discoveredPeripheral != nil && characteristic != nil && data.length > 0) {
        [discoveredPeripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
}

- (void)sendClose {
    Byte command[1] = {0x00};
    NSData *data = [NSData dataWithBytes:command length:sizeof(command)];
    [self sendData:data];
}

- (void)sendOpen {
    Byte command[1] = {0x11};
    NSData *data = [NSData dataWithBytes:command length:sizeof(command)];
    [self sendData:data];
}

-(void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [centralManager stopScan];
    if (discoveredPeripheral != nil) {
        [centralManager cancelPeripheralConnection:discoveredPeripheral];
    }
}

#pragma mark    CBCentralManager'Delegate
//检查蓝牙状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"Central Update State  检查蓝牙状态");

    switch (central.state) {
        case CBCentralManagerStatePoweredOn:{
            NSLog(@"CBCentralManagerStatePoweredOn");
            // 查找Peripheral设备
            // 如果第一个参数传递nil，则管理器会返回所有发现的Peripheral设备。
            // 通常我们会指定一个UUID对象的数组，来查找特定的设备
//            [centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];
            [centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];
        }
            break;

        case CBCentralManagerStatePoweredOff:
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;

        case CBCentralManagerStateUnsupported:
            NSLog(@"CBCentralManagerStateUnsupported");
            break;

        default:
            break;
    }
}
//查找设备结果代理
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name == %@",peripheral.name];
    if ([[serviceArr filteredArrayUsingPredicate:predicate] count] == 0) {
        NSLog(@"查找设备结果  \nDiscover name :      %@      \nide %@\n %@  \n RSSI%@", peripheral.name,peripheral.identifier,advertisementData,RSSI);
//        discoveredPeripheral = peripheral;
        [serviceArr addObject:peripheral];
        [_tableView reloadData];
//        [centralManager connectPeripheral:peripheral options:nil];
//        [centralManager stopScan];
    }
}
//连接设备失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"连接设置结果");
    if (error) {
        NSLog(@"连接失败:%@",error);
        discoveredPeripheral = nil;
    }
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    NSLog(@"连接断开%@",error);
    discoveredPeripheral = nil;
}
//连接设备成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"连接设备成功 Peripheral Connected");
    [centralManager stopScan];
    peripheral.delegate = self;
//    [peripheral discoverServices:@[ [CBUUID UUIDWithString:kServiceUUID]]];
    [peripheral discoverServices:nil];
    discoveredPeripheral = peripheral;
}
//设备中的服务
- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"查询设备中的服务");
    if (error)
    {
        NSLog(@"查询失败Error discovering service: %@", [error localizedDescription]);
        return;
    }

    for (CBService *service in aPeripheral.services)
    {
        NSLog(@"服务UUID  Service found with UUID: %@", service.UUID.UUIDString);

        if ([service.UUID.UUIDString isEqualToString:@"FFF0"]) {
            [aPeripheral discoverCharacteristics:nil forService:service];
        }
//        [aPeripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray<CBService *> *)invalidatedServices {
    NSLog(@"服务更新:%@",invalidatedServices);
}
//特定服务的特性
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"特定服务的特性  Discover Characteristics");
    for (CBCharacteristic *characteristic1 in service.characteristics)
    {
        NSLog(@"Discovered characteristic %@", characteristic1);
        [peripheral setNotifyValue:true forCharacteristic:characteristic1];
        characteristic = characteristic1;
//        [peripheral readValueForCharacteristic:characteristic];
//        Byte command[1] = {0x11};
//        NSData *data = [NSData dataWithBytes:command length:sizeof(command)];
//        [peripheral writeValue:data forCharacteristic:characteristic  type:CBCharacteristicWriteWithResponse];
//        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
//            [peripheral setNotifyValue:YES forCharacteristic:characteristic];//监听广播
//        }

    }
}
//特定服务的特性值的获取回调
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSData *data = characteristic.value;
    NSLog(@"Data = %@", data);
    if(data){
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
    }
}

#pragma mark    tableview
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return serviceArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"serviceCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    CBPeripheral *dic = [serviceArr objectAtIndex:indexPath.row];
    cell.textLabel.text = (dic.name.length>0)?dic.name:@"没有";
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",dic.identifier];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CBPeripheral *peripheral = [serviceArr objectAtIndex:indexPath.row];
    NSLog(@"开始链接%@",peripheral);
    [centralManager connectPeripheral:peripheral options:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
